package com.hm.health.Activity.ecgflash;

import static com.hm.health.MyApplication.getHBDTestClient;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;

import com.goodix.callback.AbsOnHBDTestClientListener;
import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.iot.libbase.logger.Glog;
import com.goodix.libromablecom.sdk.cardiff.CardiffConstants;
import com.goodix.libromablecom.sdk.cardiff.arguments.GetArgumentsKeyEnum;
import com.goodix.libromablecom.sdk.cardiff.arguments.SetArgumentsKeyEnum;
import com.goodix.libromablecom.sdk.cardiff.arguments.StartArgumentsKeyEnum;
import com.goodix.libtest.utils.ProgressDialogUtils;
import com.goodix.utils.SPUtils;
import com.goodix.utils.ToastUtils;
import com.goodix.widget.AlertDialogEx;
import com.hm.health.Activity.BaseActivity;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.entity.arguments.StartArgumentsManager;
import com.hm.health.records.ecgpatch.EcgPatchRecord;
import com.hm.health.service.EcgFlashService;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EcgFlashTestActivity extends BaseActivity {
    public static final String TAG = "EcgFlashTestActivity";

    @BindView(R.id.tv_continued_time)
    TextView mContinuedTimeView;
    @BindView(R.id.rb_status)
    RadioButton mRbStatus;
    @BindView(R.id.bt_oper)
    Button mBtnStartStop;
    @BindView(R.id.bt_online_mode)
    Button mBtnStartOnline;

    private EcgFlashService.EcgFlashBinder mBinder;
    private ServiceConnection mServiceConnection;
    private boolean mIsRunning;
    ProgressDialog mPdBusy;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        setContentView(R.layout.activity_ecg_flash_test);
        ButterKnife.bind(this);
        initView();
        initData();
        getHBDTestClient().registerHBDDataListener(mOnHBDDataListener);
        getHBDTestClient().registerTestCallback(mClientListener, null);
    }

    @Override
    protected void onDestroy() {
        getHBDTestClient().unRegisterHBDDataListener(mOnHBDDataListener);
        unbindService(mServiceConnection);
        getHBDTestClient().unRegisterTestCallback(mClientListener, null);
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }


    private void initView() {
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setHomeButtonEnabled(false);
            setCenterTitle(getString(R.string.ecg_flash_function));
        }
        updateStatusViewOnUIThread(false);
        initOnlineBtn();
    }

    private void initData() {
        mIsRunning = false;

        mServiceConnection = new ServiceConnection(){
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.d(TAG, "onServiceConnected");
                mBinder = (EcgFlashService.EcgFlashBinder) iBinder;
                if (mBinder != null) {
                    mBinder.registerEcgFlashCallback(mServiceCallback);
                    mIsRunning = mBinder.isEcgFlashRunning();
                    updateStatusViewOnUIThread(mIsRunning);
                    int startMode = (int)SPUtils.get(mContext, EcgFlashService.KEY_ECG_FLASH_START_MODE, EcgFlashService.NORMAL_START);
                    if (!mIsRunning && startMode == EcgFlashService.LOST_DATA_SYNC) {
                        recoverLostAlertDialog();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d(TAG, "onServiceDisconnected");
                mBinder.unregisterEcgFlashCallback(mServiceCallback);
                mBinder = null;
            }
        };

        Intent intent = new Intent(mContext, EcgFlashService.class);
        bindService(intent, mServiceConnection, Service.BIND_AUTO_CREATE);

        //状态恢复
        /*if (mBinder != null && mBinder.getMcuStatus()) {
            mBinder.recoveryStatus();
        }*/
    }

    private void recoverLostAlertDialog() {
        if (!isFinishing()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(R.string.ecg_finish_recover_get_lost_data);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (mBinder != null) {
                        StartArgumentsManager.getInstance().getRecoverBundle(mContext);
                        mBinder.recoverGetLostSector();
                    }
                }
            });
            builder.setNegativeButton(R.string.cancel, null);
            builder.show();
        }
    }

    private void initOnlineBtn() {
        mBtnStartOnline.setOnClickListener(view -> {
            new Thread(() -> {
                MyApplication.getHBDTestClient().setRunTimeFlag(SetArgumentsKeyEnum.ARG_READ_SAMPLE_DATA,
                        CardiffConstants.CARDIFF_DATA_ONLINE_ARG);
            }).start();
            Intent intent = new Intent(mContext, EcgFlashOnlineActivity.class);
            mContext.startActivity(intent);
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cardiff_demo, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.quit) {
            onActionStop();
        }
        return super.onOptionsItemSelected(item);
    }

    public void onActionStop() {
        AlertDialogEx.Builder builder = new AlertDialogEx.Builder(mContext);
        builder.setMessage(R.string.ecg_flash_exit);
        builder.setPositiveButton(R.string.quit, view -> {
            finish();
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    private void updateTimeOnUIThread(String time) {
        runOnUiThread(() -> {
            mContinuedTimeView.setText(time);
        });
    }

    private void updateStatusViewOnUIThread(boolean isRunning) {
        runOnUiThread(() -> {
            if (isRunning) {
                mRbStatus.setText(String.format(getString(R.string.ecg_flash_running), "-:-"));
                mRbStatus.setTextColor(getResources().getColor(R.color.device_connected));
                mRbStatus.setChecked(true);
                mRbStatus.setSelected(true);
                mRbStatus.setClickable(false);
                mBtnStartStop.setText(R.string.stop_measure);
                mBtnStartOnline.setVisibility(View.VISIBLE);
            } else {
                mRbStatus.setText(R.string.ecg_flash_not_run);
                mRbStatus.setTextColor(getResources().getColor(R.color.device_disconnected));
                mRbStatus.setChecked(false);
                mRbStatus.setSelected(false);
                mRbStatus.setClickable(true);
                mBtnStartStop.setText(R.string.btn_start_test);
                mBtnStartOnline.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onBackPressed() {
        ToastUtils.showShortToastMessage(mContext, getString(R.string.tips_exit_test));
    }

    @OnClick(R.id.bt_oper)
    void doOper() {
        if (mIsRunning) {
            stopTest();
        } else {
            startTest();
        }
    }

    private void startTest() {
        Glog.d(TAG, "startTest");
        mPdBusy = ProgressDialogUtils.getAndShow(mContext, getString(R.string.ecg_flash_is_starting));
        new Thread(() -> {
            Intent intent = new Intent(mContext , EcgFlashService.class);
            startService(intent);
            if (mBinder != null) {
                mBinder.startEcgFlash();
            }
        }).start();
        startOrStopTimeout(true);
    }

    private void stopTest() {
        Log.d(TAG, "stopTest");
        mPdBusy = ProgressDialogUtils.getAndShow(mContext, getString(R.string.ecg_flash_is_stopping));
        new Thread(() -> {
            if (null != mBinder) {
                mBinder.stopEcgFlash();
            }
            Intent intent = new Intent(mContext , EcgFlashService.class);
            stopService(intent);
        }).start();
        startOrStopTimeout(false);
    }

    private void startOrStopTimeout(boolean start) {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        exec.execute(() -> {
            int i = 0;
            while (true) {
                if (start) {
                    if (mBinder.isEcgFlashRunning()) {
                        break;
                    }
                } else {
                    if (!mBinder.isEcgFlashRunning()) {
                        break;
                    }
                }
                try {
                    Glog.d(TAG, "startOrStopTimeout...");
                    Thread.sleep(1000 * 2);
                    i++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (i >= 5) {
                    if (start) {
                        runOnUiThread(() -> {
                            if (mPdBusy.isShowing()) {
                                mPdBusy.dismiss();
                            }
                        });
                    } else {
                        mBinder.forceStop();
                    }
                    break;
                }
            }
        });
    }

    private void retryGetSectorId() {
        if (!isFinishing()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle(R.string.ecg_finish_connect_error);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Executors.newSingleThreadExecutor().execute(() -> {
                        mBinder.startGetLostSectorId();
                    });
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBinder.finishLostSector();
                }
            });
            builder.show();
        }
    }

    private AbsOnHBDTestClientListener mClientListener = new AbsOnHBDTestClientListener() {

        @SuppressLint("ResourceAsColor")
        @Override
        public void onDisconnected(int errCode) {
            Log.d(TAG, "onDisconnected errCode=" + errCode);
            runOnUiThread(() -> {
                mRbStatus.setTextColor(getResources().getColor(R.color.device_disconnected));
                mRbStatus.setText(R.string.ble_disconnected);
                mRbStatus.setChecked(false);
                mRbStatus.setSelected(false);
            });
        }

        @SuppressLint("ResourceAsColor")
        @Override
        public void onConnected(int errCode) {
            Log.d(TAG, "onConnected errCode=" + errCode);
            runOnUiThread(() -> {
                int sampleStatus = Integer.parseInt(
                        MyApplication.getHBDTestClient().getRunTimeFlag(GetArgumentsKeyEnum.ARG_GET_SLAVER_SAMPLE_STATUS));
                Glog.i(TAG, "sampleStatus=" + sampleStatus);
                if (sampleStatus == CardiffConstants.CARDIFF_SAMPLE_RETURN_FREE || sampleStatus == CardiffConstants.CARDIFF_RETURN_NO_RESPOND) {
                    mRbStatus.setTextColor(getResources().getColor(R.color.device_disconnected));
                    mRbStatus.setText(R.string.ecg_finish_ecg_stop);
                } else {
                    mRbStatus.setTextColor(R.color.device_connected);
                    mRbStatus.setText(String.format(getString(R.string.ecg_flash_running), "-:-"));
                }
                mRbStatus.setChecked(true);
                mRbStatus.setSelected(true);
            });
        }
    };

    private EcgFlashService.IEcgFlashServiceCallback mServiceCallback =  new EcgFlashService.IEcgFlashServiceCallback() {
        @Override
        public void onTimeUpdate(String time) {
            updateTimeOnUIThread(time);
        }

        @Override
        public void onStatusChanged(boolean isRunning) {
            Log.d(TAG, "isRunning=" + isRunning);
            mIsRunning = isRunning;
            if (mPdBusy != null) {
                runOnUiThread(() -> {
                    if (mPdBusy.isShowing()) {
                        mPdBusy.dismiss();
                    }
                });
            }
            updateStatusViewOnUIThread(isRunning);
            if (!isRunning) {
                //runOnUiThread(() -> showReadLackingPacket());
            }
        }

        @Override
        public void onGetLostSectorIdFailed() {
            runOnUiThread(() -> {
                retryGetSectorId();
            });
        }
    };

    private OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {

        @Override
        public void onDataChanged(String dataType, int[] dataArr) {
            if (dataType.equals(StartArgumentsKeyEnum.ALG_ECG_DATA_TIME_MSG)) {
                int year = dataArr[EcgPatchRecord.DATA_TIME_MSG.YEAR.ordinal()];
                int month = dataArr[EcgPatchRecord.DATA_TIME_MSG.MONTH.ordinal()];
                int date = dataArr[EcgPatchRecord.DATA_TIME_MSG.DATE.ordinal()];
                int hour = dataArr[EcgPatchRecord.DATA_TIME_MSG.HOUR.ordinal()];
                int minute = dataArr[EcgPatchRecord.DATA_TIME_MSG.MINUTE.ordinal()];
                int second = dataArr[EcgPatchRecord.DATA_TIME_MSG.SECOND.ordinal()];
                String timeStr = String.format("%04d-%02d-%02d %02d:%02d:%02d", year, month,
                        date, hour, minute, second);
                runOnUiThread(() -> {
                    if (mIsRunning){
                        mRbStatus.setText(String.format(getString(R.string.ecg_flash_running), timeStr));
                    }
                });
            }
        }

        @Override
        public void onMeasureResult(MeasureResult result) {

        }
    };

}
